
const dabaseObj = {
	Blog: "blog",
	Users: "uni-id-users",
	BlogLike: "blog-like"
}

const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	_before: function() { // 通用预处理器

	},
	async addComment({
		articleId,
		userId,
		comment,
		commentType,
		replyUserId,
		replyCommentId
	} = {}) {

		if (!articleId || !userId || !comment || (commentType != 0 && commentType != 1 && commentType != 2)) {
			return {
				errCode: "blog-commemts-addComment-params-error",
				errMsg: "参数错误",
			}
		}
		if (commentType) {
			if (!replyUserId || !replyCommentId) {
				return {
					errCode: "blog-commemts-addComment-params-error",
					errMsg: "replyUserId,replyCommentId参数错误",
				}
			}
		}

		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})

		const transaction = await db.startTransaction()
		let commentId, commentMapId, result
		try {
			commentId = await transaction.collection("blog-comment").add({
				"article_id": articleId,
				"user_id": userId,
				"comment_content": comment,
				"comment_type": commentType,
				"reply_user_id": replyUserId,
				"reply_comment_id": replyCommentId,
				"comment_date": Date.now()
			})

			if (commentType == 0) {
				result = await transaction.collection("blog").doc(articleId).update({
					"comment_count": dbCmd.inc(1)
				})
			}

			if (commentType == 1) {
				await transaction.collection("comment-index").add({
					'comment_id': commentId.id,
					'ancestor_id': replyCommentId
				})
			} else if (commentType == 2) {
				const map = await dbJQL.collection("comment-index")
					.where(`comment_id == '${replyCommentId}'`)
					.get()
				if (map.data.length > 0) {
					commentMapId = await transaction.collection("comment-index").add({
						'comment_id': commentId.id,
						'ancestor_id': map.data[0].ancestor_id
					})
				}
			}
			await transaction.commit();
		} catch (e) {
			await transaction.rollback()
		} finally {
			return commentId
		}

	},

	async getCommentList({
		articleId,
		skip = 0,
		limit = 10,
		orderBy = "date",
		order = "desc"
	} = {}) {
	
		if (!articleId) {
			return {
				errCode: "blog-commemts-getCommentList-params-error",
				errMsg: "articleId参数错误",
			}
		}
		if (typeof skip != "number" || typeof limit != "number") {
			return {
				errCode: "blog-commemts-getCommentList-params-error",
				errMsg: "skip | limit参数错误",
			}
		}
		orderBy = orderBy.toLowerCase()
		order = order.toLowerCase()
		if (orderBy != "date" && orderBy != "likeCount") {
			return {
				errCode: "blog-commemts-getCommentList-params-error",
				errMsg: "orderBy参数错误",
			}
		}
		if (order != "desc" && order != "asc") {
			return {
				errCode: "blog-commemts-getCommentList-params-error",
				errMsg: "order参数错误",
			}
		}
		if (orderBy == "date") {
			orderBy = "comment_date"
		} else {
			orderBy = "like_count"
		}
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})

		try {
			const userTemp = dbJQL.collection("uni-id-users").field("_id,avatar_file,username,nickname").getTemp()
			const parentTemp = dbJQL.collection("blog-comment")
				.where(`article_id=='${articleId}' && comment_type == 0`)
				.orderBy(`${orderBy} ${order}`)
				.skip(skip)
				.limit(limit)
				.getTemp()
			
			let parentList = await dbJQL.collection(parentTemp, userTemp)
				.foreignKey("blog-comment.user_id")
				.get()
			
			parentList = parentList.data
			const parentIndexList = parentList.map(i => i._id + '')

			// 映射表 按 ancestor_id 进行分组，并获取最大 id 的那条评论 id映射关系
			let childrenCount = await dbJQL.collection("comment-index")
				.where(`ancestor_id in ['${parentIndexList.join("','")}']`)
				.groupBy('ancestor_id')
				.groupField('count(*) as all_replay_count, max(_id) as max_id')
				.orderBy('_id desc')
				.get()
			
			// 祖先列表添加子评论总数
			childrenCount = childrenCount.data;
			childrenCount.forEach(i => {
				const parentIndex = parentIndexList.findIndex(f => f == i.ancestor_id)
				if (parentIndex !== -1) {
					parentList[parentIndex].all_replay_count = i.all_replay_count
				}

			})
			// 通过最大映射 id 获取子评论 id
			const c = childrenCount.map(i => i.max_id + '')
			const childrenTemp = await dbJQL.collection("comment-index")
				.where(`_id in ['${c.join("','")}']`)
				.get()
			const childCommentIdList = childrenTemp.data.map(i => i.comment_id + '')

			const childrenListTemp = dbJQL.collection("blog-comment")
				.where(`_id in ['${childCommentIdList.join("','")}']`)
				.field(
					'_id,article_id,user_id,comment_content,comment_type,reply_user_id,reply_comment_id,comment_date'
					)
				.orderBy(`${orderBy} ${order},_id desc`)
				.getTemp()

			let childrenList = await dbJQL.collection(childrenListTemp, userTemp)
				.get()

			childrenList = childrenList.data

			// 给子评论添加祖先 id
			childrenTemp.data.forEach(i => {
				const childIndex = childrenList.findIndex(f => f._id == i.comment_id)
				if (childIndex !== -1) {
					childrenList[childIndex].ancestor_id = i.ancestor_id
				}
			})


			// 根据子评论的祖先id，找到父级拼接
			childrenList.forEach(child => {
				let parentIndex = parentList.findIndex(f => f._id == child.ancestor_id)
				if (parentIndex !== -1) {
					if (!parentList[parentIndex].children) {
						parentList[parentIndex].children = []
					}
					child.parent_all_reply_count = parentList[parentIndex].all_replay_count
					parentList[parentIndex].children.push(child)
				}
			})
			return parentList
		} catch (e) {
			return {
				errCode: "blog-comment-getCommentList-error",
				errMsg: e.message
			}
		}
	},

	async getChildData({
		ancestor_id,
		order,
		skip
	} = {}) {
		if (!ancestor_id) {
			return {
				errCode: "blog-commemts-getChildData-params-error",
				errMsg: "ancestor_id参数错误",
			}
		}
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})

		try {
			const userTemp = dbJQL.collection("uni-id-users").field("_id,avatar_file,username,nickname")
				.getTemp()

			const indexMap = await dbJQL.collection("comment-index")
				.where(`ancestor_id == '${ancestor_id}'`)
				.orderBy("_id desc")
				.skip(skip)
				.limit(5)
				.get()

			const count = await dbJQL.collection("comment-index")
				.where(`ancestor_id == '${ancestor_id}'`)
				.count()

			const arr = indexMap.data.map(i => i.comment_id + '')

			const childTemp = dbJQL.collection("blog-comment")
				.where(`_id in ['${arr.join("','")}']`)
				.orderBy(`${order.orderField} ${order.sort}, _id desc`)
				.getTemp()
			let childData = await dbJQL.collection(childTemp, userTemp)
				.get()

			childData = childData.data
			childData.forEach(i => {
				i.parent_all_reply_count = count.total
				i.ancestor_id = ancestor_id
			})

			return childData
		} catch (e) {
			return e
		}
	},

	async getArticleCommentCount(blogIdList) {
		if (!blogIdList) {
			return []
		}
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const $ = db.command.aggregate
		try {
			const commentCountList = await dbJQL.collection("blog-comment").aggregate()
				.match({
					comment_type: dbCmd.eq(0)
				})
				.group({
					_id: "$article_id",
					allCoumentCount: $.sum(1)
				})
				.end()
			const result = []
			commentCountList.data.forEach(comment => {
				const index = blogIdList.findIndex(i => comment._id == i)
				if (index !== -1) result.push({
					index,
					count: comment.allCoumentCount
				})
			})

			return result
		} catch (e) {
			return e
		}
	},

	async commentLikeClick(id, type) {
		if (!id) {
			return {
				errCode: "blog-comment-commentLikeClick-params-error",
				errMgs: "参数缺失"
			}
		}

		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		let increasement = type ? 1 : -1
		try {
			await dbJQL.collection("blog-comment").doc(id).update({
				like_count: dbCmd.inc(increasement)
			})
		} catch (e) {
			//TODO handle the exception
			return e
		}
	},

	async queryCommentCount() {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})

		try {
			const blogList = await dbJQL.collection("blog").where("article_status == 1").get()
			const blogIndexList = blogList.data.map(i => i._id + '')
			const where = `user_id == $cloudEnv_uid && article_id in ['${blogIndexList.join("','")}']`
			const result = await dbJQL.collection("blog-comment")
				.where(where).get()
			return result.data.length
		} catch (e) {
			return {
				errCode: "123",
				errMsg:"123"
			}
		}
	}
}
